package main

import (
	"chatServer/src/msgConst"
	"chatServer/src/server"
	"fmt"
	"sort"
	"strconv"
	"strings"
	"time"
)

//GmCmd GM命令
func GmCmd() {
	for {
		var input string
		_, err := fmt.Scanln(&input)
		if err != nil {
			fmt.Println("无效命令，请重试")
			continue
		}
		args := strings.Split(input, "#")
		if len(args) < 2 {
			fmt.Println("无效命令，请重试")
			continue
		} else {
			switch args[0] {
			case msgConst.GmStats: // 用户状态查询
				userStats(args[1])
				break
			case msgConst.GmPopular: // 热度消息查询
				getPopular(args[1])
				break
			}
		}
	}
}

// 用户状态
func userStats(username string) {
	userMap := server.ChatServer.GetUserMap()
	user := userMap[username]
	if user == nil {
		fmt.Println("查无此人，此用户不存在")
	} else {
		nowTime := time.Now().Unix()
		onlineTime := nowTime - user.LoginTime
		fmt.Println("[" + username + "]:" + "登录时长:" + strconv.Itoa(int(onlineTime)) + "秒," + "房间号:" + strconv.Itoa(user.RoomID))
	}
}

// 获取热度消息
func getPopular(roomIDStr string) {
	roomID, err := strconv.Atoi(roomIDStr)
	if err != nil {
		fmt.Println("错误参数，请重新输入")
	} else {
		roomMap := server.ChatServer.GetRoomMap()
		room := roomMap[roomID]
		if room == nil {
			fmt.Println("此房间不存在，请重新输入")
		} else {
			msgMap := room.GetMsgMap()
			popularMsg := findPopular(msgMap)
			if popularMsg == "" {
				fmt.Println("当前房间还没有什么消息")
			} else {
				fmt.Println("当前房间热度消息为：" + popularMsg)
			}
		}
	}
}

// 临时排序使用结构
type kv struct {
	key   string
	value int
}

// 查找热度消息
func findPopular(msgMap map[string]int) string {
	if len(msgMap) > 0 {
		var s []kv
		for k, v := range msgMap {
			s = append(s, kv{k, v})
		}
		sort.Slice(s, func(i, j int) bool {
			return s[i].value > s[j].value
		})
		return s[0].key
	} else {
		return ""
	}
}
